#!/bin/sh /etc/rc.common
#TWAMP Reflector software
# Copyright (C) 2019 iopsys Software Solutions AB
#Author: Amin Ben Ramdhane <amin.benramdhane@pivasoftware.com>

START=99
STOP=10

USE_PROCD=1
PROG="/usr/sbin/icwmp_twampd"

start_service() {
	local id=`uci -q get cwmp_twamp.twamp.id`
	local connection=`uci show cwmp_twamp | grep "cwmp_twamp.@twamp_reflector.*id=\'$id\'" | cut -d "." -f 2`
	local enable=`uci -q get cwmp_twamp.$connection.enable`
	local interface=`uci -q get cwmp_twamp.$connection.interface`
	local port=`uci -q get cwmp_twamp.$connection.port`
	local port_list=`uci -q get cwmp_twamp.$connection.port_list`
	port_list=`echo $port_list | tr "," " "`
	if [ "$enable" = "1" ]; then
		if [ $interface = "wan" ]; then
			for str in $port_list; do
				if [ "${str/-}" != "$str" ] ; then
					str=`echo $str | tr "-" ":"`
				fi
				iptables -I zone_wan_input -p udp --dport "$str" -j ACCEPT -m comment --comment "Open UDP allowed port"
				iptables -I zone_wan_input -p tcp --dport "$port" -j ACCEPT -m comment --comment "Open TCP allowed port"
			done		
		fi
		procd_open_instance
		procd_set_param command "$PROG"
		procd_set_param respawn "3" "7" "0"
		procd_close_instance
	else
		if [ $interface = "wan" ]; then
			if [ "${str/-}" != "$str" ] ; then
				str=`echo $str | tr "-" ":"`
			fi
			iptables -I zone_wan_input -p udp --dport "$str" -j REJECT -m comment --comment "Close UDP allowed port"
			iptables -I zone_wan_input -p tcp --dport "$port" -j REJECT -m comment --comment "Close TCP allowed port"
		fi
	fi
}

boot() {
	start
}

reload_service() {
	stop
	start 
}

service_triggers() {
	procd_add_reload_trigger cwmp_twamp
}
